<!--  -->
<template>
  <div class="shopcart">
      <!-- <HeaderTop title="购物车"></HeaderTop> -->
      <section class="shopcart-wrapper">
        <div class="shopcart-list" v-if="token">     
          <ul class="shopcart-list-ul" v-if="CartList.length">
            <!-- <mt-loadmore  v-if='CartList' :top-method="loadTop" :bottom-method="loadBottom"  :bottom-all-loaded="allLoaded" :bottom-drop-text="bottomText"  ref="loadmore"> -->
            <li
              class="shopcart-list-li"
              v-for="(goods, index) in CartList"
              :key="index">
              <div class="cBox">
                <van-checkbox v-model="goods.isCheck" @change="checkSelect" checked-color="#145B3E"></van-checkbox>
              </div>
              <div class="goodsImg-wrapper">
                <div class="goodsImg" @click="$router.push({path: '/goodsdetail', query: {id: goods.itemId}})" :style="{backgroundImage:'url(' + goods.cartImg + ')'}"></div>
                <!-- <img class="goodsImg" :src="goods.cartImg"
                @click="$router.push({path: '/goodsdetail', query: {id: goods.itemId}})"> -->
              </div>
              <div class="goods">
                <h3 v-html="goods.itemName"></h3>
                <p>
                  <span>{{goods.weights}}</span>
                  &ensp;
                  <span>单价: {{goods.price}}</span>
                </p>
                <van-stepper v-model="goods.num" @change="updateGoodsNum(goods); getAllMoney()" />
              </div>
              <img class="del" src="./img/shanchu.png" @click="removeTbCart(goods)">
            </li>
            <!-- </mt-loadmore> -->
            <p @click='loadBottom' class='allloaded' v-if='!allLoaded'>点击加载更多</p>
            <p v-else class='allloaded'>没有更多数据</p>
          </ul>
          <div v-else  class='noGoods'> <img class="noGoodsImg" src="../../assets/img/noData.png" alt=""> </div>
           <!-- <div class="noGoods" v-else>购物车暂无商品</div> -->
        </div>
        <div class="noLogin" v-if="!token">您还没有登录,请去<span class="noLoginButton" @click="$router.push('/login')">登录</span></div>
        <div class="shopcart-submit">
          <span @click="selectAll">
            <van-checkbox v-model="checked" checked-color="#145B3E">全选</van-checkbox>
          </span>
          <p>总计：<span>￥{{allMoney}}</span></p>
          <button @click="toConfirmorder">结算</button>
        </div>
      </section>
  </div>
</template>

<script>
// import HeaderTop from '../../components/HeaderTop/HeaderTop'
import { Loadmore } from 'mint-ui'
export default {
  data () {
    return {
      CartList: [],
      checked: false,
      value:1,
      allMoney: 0,
      userId:'',
      token:'',
      num:1,
      size:10,
      allLoaded:false,
      // autofill:false,
      // bottomText:"上拉加载更多",
      // loadMoreConfig:{
      //     bottomDistance:100,
      // }
    };
  },
  components: {
    // HeaderTop,
    'mt-loadmore':Loadmore
  },
  created () {
    this.userId = localStorage.getItem('userId');
    this.token = localStorage.getItem('token');
    this.getCartList()
  },
  methods: {
    // 查看购物车
    async getCartList () {
      if(this.token){
        const params = {
          userId: this.userId,
          token: this.token,
          num: this.num,
          size: this.size
        }
        console.log(params)
        const result = await this.API.reqSelectTbCart(params)
        result.retData.forEach(item => {
          item.isCheck = false
        })
        this.CartList = result.retData
        console.log('购物车数据',this.CartList)
      }
    },
     //获取更多数据
    async getListDataPull(){
      if(this.allLoaded == true){
        return;
      }
        console.log('num',this.num)
        let result = await this.API.reqSelectTbCart({
        userId: this.userId,
        token: this.token,
        num: this.num,
        size: this.size
      })
        console.log(result)
        if(result.retData==''||result.retData==[]||result.retData==null){
            this.isHaveMore(false) //禁止上拉
        }else{
            result.retData.forEach(item => {
              item.isCheck = false
            })
            this.CartList = this.CartList.concat(result.retData?result.retData:[]);
            this.isHaveMore(true)
        }
    },
    // //下拉刷新
    // loadTop(){
    //   let self = this;
    //   this.num = 1;
    //   this.allLoaded = false;
    //   setTimeout(function(){
    //     self.getCartList();
    //     self.$refs.loadmore.onTopLoaded();
    // },1000)
    // },
    // // 上拉加载
    loadBottom(){
        let self = this;
        self.num ++;
        console.log('loadmore',this.num)
        setTimeout(function(){
            // if(this.getCartList){
            //   self.$refs.loadmore.onBottomLoaded();
            // }
            self.getListDataPull();
        },1000)
    },
    isHaveMore(isHaveMore){
        this.allLoaded = true; //true是禁止上拉加载
        if(isHaveMore){
          this.allLoaded = false;
          
        }
    },
    // 单点选择
    checkSelect () {
      this.checked = this.CartList.every(item => item.isCheck)
      this.getAllMoney()
    },
    // 全选或全不选
    selectAll () {
      this.CartList.forEach(item => item.isCheck = this.checked)
      this.getAllMoney()
    },
    // 获取当前总金额
    getAllMoney () {
      let sub = 0
      this.CartList.forEach(item => {
        if (item.isCheck) {
          sub += item.num * item.price
        }
      })
      this.allMoney = sub
    },
    // 删除商品
    async removeTbCart(item){
      const params = {
        userId: localStorage.getItem('userId'),
        token: localStorage.getItem('token'),
        tbCartIds: String(item.id)
      }
      const result = await this.API.reqRemoveTbCart(params)
      this.$toast('删除成功')
      // 移除该项, 这里并不请求新的数据, 以避免选择状态被改变
      this.CartList.forEach((good, index) => {
        if (good.id == item.id) {
          this.CartList.splice(index, 1)
        }
      })
    },
    // removeTbCart (item) {
    //   this.$dialog.confirm({
    //     message: '是否删除该商品'
    //   }).then(async () => {
    //     const params = {
    //       userId: localStorage.getItem('userId'),
    //       token: localStorage.getItem('token'),
    //       tbCartIds: String(item.id)
    //     }
    //     const result = await this.API.reqRemoveTbCart(params)
    //     this.$toast('删除成功')
    //     // 移除该项, 这里并不请求新的数据, 以避免选择状态被改变
    //     this.CartList.forEach((good, index) => {
    //       if (good.id == item.id) {
    //         this.CartList.splice(index, 1)
    //       }
    //     })
    //   }).catch(() => {}) 
    // },
    // 修改商品数量
    async updateGoodsNum (item) {
      const params = {
        userId: localStorage.getItem('userId'),
        token: localStorage.getItem('token'),
        tbCartId: String(item.id),
        num: item.num
      }
      const result = await this.API.reqUpdateTbcartNum(params)
    },
    // 结算购物车
    toConfirmorder () {
      const arr = []
      this.CartList.forEach(item => {
        if (item.isCheck) {
          arr.push(item.id)
        }
      })
      this.$store.state.shopIdArray = arr
      if (arr.length !== 0) {
        this.$toast('结算购物车')
        this.$router.push('/confirmorder')
      }
    },
    onSubmit(){
      alert(1111)
    }
  },
}

</script>


<style lang='stylus'>
  .cBox 
    .van-checkbox
      .van-checkbox__icon
        margin-bottom 35px
</style>

<style lang='stylus' scoped>
  @import "../../common/stylus/mixins.styl"
  .shopcart
    width 100%
    min-height 85%
    padding-bottom 0 !important
    background #fff
    position relative
    .shopcart-wrapper
      width 100%
      // top-border-1px(#e4e4e4)
      .shopcart-submit
        display flex
        justify-content space-around
        border 1px solid #eeeeee
        width 100%
        height 48px
        line-height 48px
        position fixed
        bottom 50px
        background #fff
        p
          margin-left 30px
          margin-right -15px
          span 
            color red
        button 
          margin 0
          padding 0
          height 35px
          line-height 35px
          border 1px solid red
          outline none
          background #fff
          padding 0 25px
          margin-top 5px
          border-radius 25px
          color red
          font-size 14px
      .shopcart-list
        height 100%
        // margin-bottom 120px
        .shopcart-list-ul
          height 550px
          padding-bottom 60px
          // margin-bottom 50px
          overflow-y scroll
        .noGoods
          text-align center
          font-size 20px
          padding-top 30px
          .noGoodsImg
            width 150px
        .shopcart-list-li
          display flex
          justify-content space-between
          padding 20px
          height 110px
          bottom-border-1px(#e4e4e4)
          .cBox
            height 110px
            margin-top 45px
            // line-height 110px
          .goodsImg-wrapper
            width 110px
            height 110px
            border-radius 5px
            border 1px solid #ccc
            overflow hidden
            .goodsImg
              width 110px
              height 110px
              background-size cover
              background-repeat no-repeat
              background-position center center
          .goods
            padding-right 20px
            display flex
            flex-flow: column
            justify-content space-between
          .del
            width 12px
            height 12px
      .noLogin
        text-align center
        font-size 20px
        height 100%
        padding-top 40px
        padding-bottom 40px
        .noLoginButton
          display inline-block
          color #fff
          background #145B3E
          padding 5px 10px
          border-radius 5px
.allloaded
   width 100% 
   text-align center
   margin-top 20px
   padding-bottom 60px
   color #565656
</style>